package services;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DataAccess.FileShareDA;

import pojo.FileSharePOJO;

/**
 * Servlet implementation class ShareFileServlet
 */
@WebServlet("/FileDownloadServlet")
public class FileDownloadServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;	
	private static final int BYTES_DOWNLOAD = 1024;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FileDownloadServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
			ServletContext ctx = getServletContext();
			int idFile =Integer.parseInt(getParameter(request, Protocol.ID));
			FileSharePOJO fs=new FileShareDA().get(idFile);
			if(fs==null){
				System.out.print("file=null");
				return;
			} 
			String fileName=fs.getPath();
			String filePath =Protocol.DIR + "/" + fileName;
			InputStream is = ctx.getResourceAsStream(filePath);
			String contentType = getServletContext().getMimeType(filePath);
			System.out.println(fileName);
			System.out.println(contentType);

			response.setContentLength(is.available());
			response.setContentType(contentType);
			response.setHeader("Content-Disposition", "attachment;filename=" + fs.getTenFile());

			int read = 0;
			byte[] bytes = new byte[BYTES_DOWNLOAD];
			OutputStream os = response.getOutputStream();

			while ((read = is.read(bytes)) != -1) {
				os.write(bytes, 0, read);
			}
			os.flush();
			os.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}
